<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2017/12/14
 * Time: 0:14
 */

namespace controller;


use controller\base\Base;
use model\Releases;
use model\Ticket;
use model\User;
use model\WechatConfig;

class Vote extends Base
{
    /**
     * @param int $id id
     * @param int $rid rid
     * @return array
     */
    public function vote($id, $rid)
    {
        $this->header($id);
        if ($this->actionListData['is_attention']) {
            $this->attention();
        }

        if (!$this->is_vote) {
            return ['state' => false, 'msg' => '投票时间未开始'];
        }
        if ($this->is_vote_end) {
            return ['state' => false, 'msg' => '投票时间已结束'];
        }

        $today = date("Y-m-d", time());
        $vote  = new \model\Vote();
        $vote->where('created', $today, '>=');
        $result = $vote->row(['releases_id' => $rid, 'action_id' => $id,'openid'=> session('openid')]);
        if (!empty($result)) {
            return ['state' => false, 'msg' => '已经投票过了'];
        }

        $ticket = new Ticket();
        $result = $ticket->minusNum($id,1);
        if ($result) {
            $releases = new Releases();
            $releases->addPoll($id, $rid, 1);
            $vote->insert([
                'releases_id' => $rid,
                'created'     => now(),
                'openid'      => session('openid'),
                'action_id'   => $id
            ]);
            return ['state' => true];
        } else {
            return ['state' => false, 'msg' => '投票次数不足'];
        }
    }

    private function attention()
    {
        $wechatConfig = new WechatConfig();
        $config       = $wechatConfig->row(['id' => $this->wx_id]);
        $access_token = $config['access_token'];
        $openid       = session('openid');

        $data = http("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
        $data = json_decode($data, true);
        if ($data['subscribe'] == 0) {
            echo json(['state' => false, 'msg' => 'unAttention']);
            exit();
        } else {
            $user = new User();
            $user->update([
                'nickname'   => $data['nickname'],
                'sex'        => $data['sex'],
                'city'       => $data['city'],
                'country'    => $data['country'],
                'province'   => $data['province'],
                'headimgurl' => $data['headimgurl'],
            ]);
        }
    }
}